//
//  SortableController+SnapshotView.swift
//
//  Created by 谢强 on 15/03/2018.
//  Copyright © 2018 谢强. All rights reserved.
//

import UIKit

// MARK: - 快照
extension SortableController {
    
    /// 添加快照
    func snapshot_createFromCell(at indexPath: IndexPath) {
        // 校验
        guard let tableView = tableView, let superview = tableView.superview else { return }
        
        // 清空
        snapshot_remove()
        tableView.reloadData()
        
        // 创建
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        let cellFrame = tableView.convert(cell.frame, to: superview)
        // 去除底部分割线
        let snapshotSize = CGSize(width: cellFrame.size.width, height: cellFrame.size.height - 1)
        
        if cellTransparent {
            // cell背景透明
            let originBackgroundColor = cell.layer.backgroundColor
            
            UIGraphicsBeginImageContextWithOptions(snapshotSize, false, 0)
            
            // 透明背景
            cell.layer.backgroundColor = UIColor(white: 1, alpha: 0.2).cgColor
            cell.layer.opacity = 0.85
            
            cell.layer.render(in: UIGraphicsGetCurrentContext()!)
            let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            // 还原背景
            cell.layer.backgroundColor = originBackgroundColor
            cell.layer.opacity = 1
            
            let imageView = UIImageView(image: snapshotImage)
            
            let shadowView = UIView()
            shadowView.frame = cellFrame
            
            let topLine = UIView()
            topLine.backgroundColor = UIColor(white: 0.6, alpha: 0.5)
            topLine.layer.shadowOffset = CGSize(width: 0, height: -1)
            topLine.layer.shadowColor = UIColor.black.cgColor
            topLine.layer.shadowRadius = 1
            topLine.layer.shadowOpacity = 1
            
            let bottomLine = UIView()
            bottomLine.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
            bottomLine.layer.shadowOffset = CGSize(width: 0, height: 2)
            bottomLine.layer.shadowColor = UIColor.black.cgColor
            bottomLine.layer.shadowRadius = 2
            bottomLine.layer.shadowOpacity = 1
            
            shadowView.addSubview(imageView)
            shadowView.addSubview(topLine)
            shadowView.addSubview(bottomLine)
            
            topLine.frame = CGRect(x: 0, y: 1, width: cellFrame.size.width, height: 0.7)
            imageView.frame = CGRect(x: 0, y: 0, width: cellFrame.size.width, height: cellFrame.size.height)
            bottomLine.frame = CGRect(x: 0, y: cellFrame.size.height - 1, width: cellFrame.size.width, height: 1.5)
            
            // 添加
            superview.addSubview(shadowView)
            snapshotView = shadowView
        } else {
            // cell背景不透明
            UIGraphicsBeginImageContextWithOptions(snapshotSize, false, 0)
            cell.layer.render(in: UIGraphicsGetCurrentContext()!)
            let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            let imageView = UIImageView(image: snapshotImage)
            
            imageView.frame = cellFrame

            imageView.layer.masksToBounds = false
            imageView.layer.opacity = Float(cellOpacity)
            imageView.layer.transform = CATransform3DMakeScale(cellScale, cellScale, 1)

            imageView.layer.shadowColor = shadowColor.cgColor
            imageView.layer.shadowOpacity = Float(shadowOpacity)
            imageView.layer.shadowRadius = shadowRadius
            imageView.layer.shadowOffset = shadowOffset
            
            // 添加
            superview.addSubview(imageView)
            snapshotView = imageView
        }
    }
    
    /// 移除快照
    func snapshot_remove() {
        snapshotView?.removeFromSuperview()
        snapshotView = nil
    }
    
    /// 位置更新
    func snapshot_updatePosition() {
        guard
            case SortState.updating(let context) = sortState,
            let tableView = tableView
        else { return }
        
        var newCenterY = context.touchPosition.y + context.snapshotOffset
        
        let safeAreaFrame: CGRect
        if #available(iOS 11, *) {
            safeAreaFrame = UIEdgeInsetsInsetRect(tableView.frame, tableView.safeAreaInsets)
        } else {
            safeAreaFrame = UIEdgeInsetsInsetRect(tableView.frame, tableView.scrollIndicatorInsets)
        }
        
        newCenterY = min(newCenterY, safeAreaFrame.maxY)
        newCenterY = max(newCenterY, safeAreaFrame.minY)
        
        snapshotView?.center.y = newCenterY
    }
    
    /// 进入动画
    func snapshot_animateIn() {
        guard let snapshotView = snapshotView else { return }
        
        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = 1
        opacityAnimation.toValue = cellOpacity
        opacityAnimation.duration = animationDuration
        
        let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
        shadowAnimation.fromValue = 0
        shadowAnimation.toValue = shadowOpacity
        shadowAnimation.duration = animationDuration
        
        let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
        transformAnimation.fromValue = 1
        transformAnimation.toValue = cellScale
        transformAnimation.duration = animationDuration
        transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        
        snapshotView.layer.add(opacityAnimation, forKey: nil)
        snapshotView.layer.add(shadowAnimation, forKey: nil)
        snapshotView.layer.add(transformAnimation, forKey: nil)
    }
    
    /// 消失动画
    func snapshot_animateOut() {
        guard let snapshotView = snapshotView else { return }
        
        let opacityAnimation = CABasicAnimation(keyPath: "opacity")
        opacityAnimation.fromValue = cellOpacity
        opacityAnimation.toValue = 1
        opacityAnimation.duration = animationDuration
        
        let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
        shadowAnimation.fromValue = shadowOpacity
        shadowAnimation.toValue = 0
        shadowAnimation.duration = animationDuration
        
        let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
        transformAnimation.fromValue = cellScale
        transformAnimation.toValue = 1
        transformAnimation.duration = animationDuration
        transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        
        snapshotView.layer.add(opacityAnimation, forKey: nil)
        snapshotView.layer.add(shadowAnimation, forKey: nil)
        snapshotView.layer.add(transformAnimation, forKey: nil)
        
        snapshotView.layer.opacity = 1
        snapshotView.layer.shadowOpacity = 0
        snapshotView.layer.transform = CATransform3DIdentity
    }
}
